//
//  LGTopicTableViewController.m
//  dw
//
//  Created by Apple on 15/12/7.
//  Copyright © 2015年 Apple. All rights reserved.
//

#import "LGTopicTableViewController.h"
#import "LGTopicCell.h"
#import "LGTopic.h"
#import "LGTopicDetailController.h"

@interface LGTopicTableViewController ()

@property (nonatomic , strong) NSMutableArray *topics;

@property (nonatomic , assign) NSInteger page;

@end

@implementation LGTopicTableViewController
/** cell重用ID */
static NSString *ID = @"TopicCell";

/** 有数据时候刷新 */
- (void)setTopics:(NSMutableArray *)topics {
    _topics = topics;
    [self.tableView reloadData];
}

#pragma -mark /***************** 生命周期 *****************/
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 注册cell
    [self.tableView registerClass:[LGTopicCell class] forCellReuseIdentifier:ID];
    
    // 直接刷新
    [self loadData];
    
    
    // 下拉刷新
    self.refreshControl = [[UIRefreshControl alloc] init];
    [self.refreshControl addTarget:self action:@selector(loadData) forControlEvents:UIControlEventValueChanged];
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

- (void)loadData {
    
    [LGTopic topicWithSuccessBlock:^(NSArray *array) {
        self.topics = [NSMutableArray arrayWithArray:array];
        self.page = 1;
    } errorBlock:^(NSError *error) {
        NSLog(@"%@",error);
    }];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self.refreshControl endRefreshing];
    });
    
}


#pragma -mark /***************** 数据源方法 *****************/

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.topics.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    LGTopicCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    
    if (cell == nil) {
        cell = [[LGTopicCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        
    }
    cell.textLabel.text = [NSString stringWithFormat:@"%zd",indexPath.row];
    
    cell.topicModel = self.topics[indexPath.row];
    return cell;
}

#pragma -mark /***************** 代理方法 *****************/
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 245;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
    LGTopicDetailController *vc = [[LGTopicDetailController alloc] init];
    vc.topicModel = self.topics[indexPath.row];
    [self.navigationController pushViewController:vc animated:YES];
    
    
    // 选中后 取消
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView.contentOffset.y > (self.topics.count - 2) * 245 - 64) {
        NSMutableDictionary *parameter = [[NSMutableDictionary alloc] init];
        parameter.dictionary =
        @{@"Appid":@"10000024",
          @"Appkey":@"824b2a4e7ca1b804c6a1a0537c0bc212",
          @"act":@"lists",
          @"client_ver":@"1.2.1",
          @"mid":@"e553e2d24021fb8a156296b27e95fe3e4cf40791",
          //@"page":@"2",
          @"platform":@"iPhone9.1",
          @"yd_auth":@"d4f6ZD7td1cA6eH0SFATxSF07DKOXB%2B7gHKhfLtmV8FYgoK%2BUm4Wp%2FCaZti6tWV75B%2FtEtCn12jixPPuZvdHoYAe%2FFntpIYn2dLpN89taV3K1vhT3Q%2BBDBixLRwmKZwel%2BXn",
          @"yd_key":@"9563klroXuyAUEc61OJWViLHGR%2BCzHgbhYmyhwkZYSJ3",
          @"yd_uid":@"7014"};
        self.page++;
        [parameter setObject:[NSNumber numberWithInteger:self.page] forKey:@"page"];
        [[LGNetworkTools sharedManager] POST:@"/topic" parameters:parameter constructingBodyWithBlock:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
            NSArray *array = responseObject[@"data"];
            
            [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                LGTopic *topic = [LGTopic topicWithDict:obj];
                [self.topics addObject:topic];
            }];
            
            [self.tableView reloadData];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            NSLog(@"错误%@",error);
        }];
    }
}
@end
